package com.ash.servlet;

import com.alibaba.fastjson.JSONArray;
import com.ash.dao.imp.DaoImpl;
import com.ash.entity.Constant;
import com.ash.entity.Role;
import com.ash.entity.User;
import com.ash.service.impl.RoleServiceImpl;
import com.ash.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : Chen Chao
 * @encoding : UTF-8
 * @date : 2020/12/27 14:57
 * @file : test06.${PACKAGE_NAME}.${NAME}.java
 * @software : IntelliJ IDEA
 * @since : 1.8
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("欢迎来到userServlet====================");
        String method = req.getParameter("method");
        System.out.println(method);
        /*servlet复用*/
        if(Constant.USER_ENSURE_PASSWORD.equals(method)){
            ensurePwd(req,resp);
        }else if(Constant.USER_MODIFY_PASSWORD.equals(method)){
            modifyPwd(req,resp);
        }else if(Constant.USER_SELECT.equals(method)){
            selectUser(req,resp);
        }else if(Constant.USER_ADD.equals(method)){
            addUser(req,resp);
        }else if(Constant.ROLE_LIST.equals(method)){
            roleList(req,resp);
        }else if(Constant.USER_EXIST.equals(method)){
            userExist(req,resp);
        }else if(Constant.USER_MODIFY.equals(method)){
            userModify(req,resp);
        }else if(Constant.USER_DELETE.equals(method)){
            userDelete(req,resp);
        }else if(Constant.USER_VIEW.equals(method)){
            userView(req,resp);
        }
    }

    private void userView(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("欢迎来到用户信息查看页面");
        userSelectByCode(req);
        req.getRequestDispatcher("jsp/userView.jsp").forward(req,resp);
    }

    /**
     * 根据UserCode查询指定用户
     * @param req 请求
     */
    private void userSelectByCode(HttpServletRequest req)  {
        /*获取信息*/
        String userCode = req.getParameter("userCode");
        DaoImpl<User> userDao = new DaoImpl<>(User.class,"userCode");
        /*执行操作*/
        User user = userDao.selectByKey(userCode);
        /*写回信息*/
        req.setAttribute(Constant.USER_SESSION,user);
    }

    /**
     * 删除用户
     * @param req 请求
     * @param resp 响应
     * @throws IOException Io异常
     */
    private void userDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /*ajax异步刷新*/
        resp.setContentType("application/json");
        /*获取信息*/
        String userCode = req.getParameter("userCode");
        DaoImpl<User> userDao = new DaoImpl<>(User.class, "userCode");
        User user = new User();
        user.setUserCode(userCode);
        /*执行操作*/
        String deleteResult = (userDao.delete(user) == 0 ? "Failure" : "Success");
        resp.getWriter().println(JSONArray.toJSONString(deleteResult));
    }

    /**
     * 从请求参数中封装实体对象
     * @param req 请求
     * @return 返回封装的实体对象
     */
    private User parameterToEntity(HttpServletRequest req){
        /*获取信息*/
        Map<String, String[]> parameterMap = req.getParameterMap();
        User user = new User();
        try {
            /*日期注册转换器*/
            DateConverter converter = new DateConverter();
            converter.setPattern("yyyy-MM-dd");
            ConvertUtils.register(converter,Date.class);
            /*封装信息*/
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException | InvocationTargetException  e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 用户信息修改
     * @param req 请求
     * @param resp 响应
     * @throws ServletException servlet异常
     * @throws IOException IO异常
     */
    private void userModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("欢迎来到用户信息修改页面");
        userSelectByCode(req);
        if(req.getAttribute(Constant.USER_SESSION)!=null) {
            UserServiceImpl userService = new UserServiceImpl();
            int update = userService.update(parameterToEntity(req));
            req.setAttribute("result", update == 0 ? "Failure" : "Success");
        }
        req.getRequestDispatcher("jsp/userModify.jsp").forward(req,resp);
    }

    /**
     * 查询添加的用户名是否存在 以json形式返回user
     * @param req req请求
     * @param resp 响应
     * @throws IOException IO异常
     */
    private void userExist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json");
        /*获取信息*/
        String userCode = req.getParameter("userCode");
        User user = new User();
        user.setUserCode(userCode);
        /*执行查询*/
        UserServiceImpl userService = new UserServiceImpl();
        User login = userService.login(user);
        /*返回结果*/
        PrintWriter writer = resp.getWriter();
        if(login==null){
            writer.write(JSONArray.toJSONString(new User()));
            System.out.println("用户不存在");
        }else {
            writer.write(JSONArray.toJSONString(user));
            System.out.println("用户存在");
        }
    }

    /**
     * 查询角色列表 以json形式返回
     * @param req 请求
     * @param resp 响应
     * @throws IOException IO异常
     */
    private void roleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json");
        Object attribute = req.getSession().getAttribute(Constant.ROLE_LIST);
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(attribute));
        System.out.println(JSONArray.toJSONString(attribute));
    }

    /**
     *
     * 添加用户
     * @param req 请求
     * @param resp 响应
     * @throws ServletException 异常
     * @throws IOException 异常
     */
    private void addUser(HttpServletRequest req,HttpServletResponse resp ) throws ServletException, IOException {
        /*把封装的实体对象进行添加操作*/
        UserServiceImpl userService = new UserServiceImpl();
        int add = userService.add(parameterToEntity(req));
        /*返回结果*/
        req.setAttribute("result",add==0?"Failure":"Success");
        req.getRequestDispatcher("jsp/useradd.jsp").forward(req,resp);
    }

    /**
     * 验证密码，并返回对应的result给前端
     * @param req 请求
     * @param resp 响应
     */
    protected void ensurePwd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("欢迎来到ensurePwd");
        /*判断密码并返回结果*/
        HashMap<String, String> map = new HashMap<>(4);
        /*获取数据*/
        User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
        String oldPassword = req.getParameter("oldPassword");
        /*执行判断*/
        if(user==null){
            /*情况一:session过期*/
            map.put("result","sessionError");
        }
        else if(oldPassword==null){
            /*情况二:输入密码为空*/
            map.put("result","error");

        }else if(oldPassword.equals(user.getUserPassword())){
            /*情况三:输入密码正确*/
            map.put("result","true");
        }
        else{
            /*情况四:输入密码错误*/
            map.put("result","false");
        }
        /*发送数据*/
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(map));


    }

    /**
     * 修改用户密码
     * @param req  请求
     * @param resp 响应
     * @throws IOException 异常
     */
    protected void modifyPwd(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("欢迎来到modifyPwd");
        /*获取信息*/
        String newPassword = req.getParameter("newPassword");
        User newUser = new User();
        User oldUser = (User) req.getSession().getAttribute(Constant.USER_SESSION);
        UserServiceImpl userService = new UserServiceImpl();
        /*执行判断*/
        /*情况一:session过期,直接跳转登录页面*/
        if(oldUser == null){
            req.setAttribute("message","登录过期，请重新登录");
        }

        else {
            /*情况二:正确获取session用户，移除session*/
            Integer id = oldUser.getId();
            newUser.setUserPassword(newPassword);
            newUser.setId(id);
            userService.update(newUser);
            req.getSession().removeAttribute(Constant.USER_SESSION);
            req.setAttribute("message","密码修改成功，请重新登录");
        }
        req.getRequestDispatcher("jsp/pwdModify.jsp").forward(req,resp);
    }

    /**
     * 类别查询与模糊查询用户
     * @param req 请求
     * @param resp 响应
     * @throws IOException IO异常
     * @throws ServletException 异常
     */
    protected void selectUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        /*获取service对象*/
        UserServiceImpl userService = new UserServiceImpl();
        RoleServiceImpl roleService = new RoleServiceImpl();
        /*获取信息*/
        String queryUserName = req.getParameter("queryUserName");
        String queryUserRoleStr = req.getParameter("queryUserRole");
        Integer queryUserRole=null;
        /*填入信息进行处理*/
        if(queryUserRoleStr!=null&&queryUserRoleStr.length()>0){
            queryUserRole=Integer.parseInt(queryUserRoleStr);
        }
        List<User> users = userService.selectUser(queryUserRole, queryUserName);
        List<Role> roleList = roleService.getRoleList();
        /*重定向返回*/
        req.getSession().setAttribute(Constant.USER_QUERY_LIST,users);
        req.getSession().setAttribute(Constant.ROLE_LIST,roleList);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRoleStr);

        System.out.println("数量:"+users.size());
        for (User user : users) {
            System.out.println(user);
        }
        req.getRequestDispatcher("jsp/userList.jsp").forward(req,resp);

    }
}
